import { useState } from 'react'
import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import { useDispatch } from 'react-redux'
import { useHistory, useLocation } from 'react-router-dom'
import { login } from '@/store/actions/login'
import logo from '@/assets/logo.png'
import './index.scss'
export default function Login() {
  const dispatch = useDispatch()
  const history = useHistory()
  const location = useLocation()
  const [loading, setLoading] = useState(false)
  const onFinish = async (values) => {
    setLoading(true)
    try {
      await dispatch(login(values))
      message.success('登录成功', 1, () => {
        // 修复
        const from = location.state ? location.state.from : '/home'
        history.replace(from)
      })
    } catch (e) {
      const msg = e.response?.data?.message
      if (!msg) return setLoading(false)
      message.error(msg, 1, () => setLoading(false))
    }
  }
  return (
    <div className='login'>
      <Card className='login-container'>
        {/* Logo */}
        <img className='login-logo' src={logo} alt='极客园' />
        {/* 默认 onChange 或者提交表单的时候会校验，也可以通过 validateTrigger 来指定其他触发校验的时机 */}
        <Form
          autoComplete='off'
          size='large'
          validateTrigger={['onBlur', 'onChange']}
          onFinish={onFinish}
          initialValues={{
            mobile: '13911111111',
            code: '246810',
            agree: true,
          }}
        >
          <Form.Item
            name='mobile'
            rules={[
              {
                required: true,
                message: '请输入手机号',
              },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号码格式不对',
              },
            ]}
          >
            <Input placeholder='请输入手机号' />
          </Form.Item>

          <Form.Item
            name='code'
            rules={[
              { len: 6, message: '验证码6个字符' },
              { required: true, message: '请输入验证码' },
            ]}
          >
            <Input placeholder='请输入验证码' maxLength={6} />
          </Form.Item>

          <Form.Item
            name='agree'
            valuePropName='checked'
            rules={[
              {
                validator: (rule, value) => {
                  if (value === true) {
                    return Promise.resolve()
                  } else {
                    return Promise.reject(new Error('请阅读并同意条款和协议'))
                  }
                },
              },
            ]}
          >
            <Checkbox>我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button type='primary' htmlType='submit' block loading={loading}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
